<template>
  <div class="member-ship">
    <BreadCrumb title="VIP会员中心"></BreadCrumb>
    <div class="member-ship-content">
      <el-card class="big-card">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <!-- Tab 1: VIP 会员类型 -->
          <el-tab-pane  label="会员类型" name="vipTypes">
            <div class="vip-types">
              <el-card
                v-for="vipType in vipTypes"
                :key="vipType.vipTypeId"
                class="vip-type-card"
              >
                <h3>{{ vipType.vipType }}</h3>
                <p>价格: {{ vipType.price }} 元</p>
                <p>可享折扣: {{ (vipType.discountRate * 10).toFixed(2) }} 折</p>
                <el-button
                  type="primary"
                  size="small"
                  @click="purchaseVip(vipType.vipTypeId)"
                  >购买</el-button
                >
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 支付对话框 -->
          <!-- 支付对话框 -->
          <el-dialog title="支付订单" :visible.sync="paymentDialogVisible" width="30%">
            <el-form :model="payForm" label-width="75px" class="pay-form" ref=payForm :rules="payRules">
              <el-form-item label="支付方式" prop="paymentMethod">
                <el-select
                  v-model="payForm.paymentMethod"
                  placeholder="请选择支付方式"
                  style="width: 100%;"
                >
                  <el-option
                    label="支付宝(暂且仅支持余额支付)"
                    value="alipay"
                  ></el-option>
                  <el-option
                    label="微信支付(暂且仅支持余额支付)"
                    value="wechat"
                  ></el-option>
                  <el-option label="余额支付" value="余额支付"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="支付密码" prop="password">
                <el-input
                  type="password"
                  v-model="payForm.password"
                  placeholder="请输入支付密码"
                ></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="paymentDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="payOrder">支付</el-button>
            </span>
          </el-dialog>

          <!-- Tab 2: 已购买的VIP信息 -->
          <el-tab-pane label="已购会员" name="vipInfo">
            <el-table :data="vipInfoList" border style="width: 100%">
              <el-table-column
                prop="vipType"
                label="会员类型"
              ></el-table-column>
              <el-table-column
                prop="discountRate"
                label="可享折扣"
              ></el-table-column>
              <el-table-column
                prop="startTime"
                label="会员生效时间"
              ></el-table-column>
              <el-table-column
                prop="endTime"
                label="会员失效时间"
              ></el-table-column>
              <el-table-column prop="status" label="会员状态"></el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- Tab 3: 订单历史 -->
          <el-tab-pane label="订单历史" name="vipOrders">
            <el-table :data="vipOrders" border style="width: 100%">
              <el-table-column
                prop="vipOrderId"
                label="订单ID"
              ></el-table-column>
              <el-table-column
                prop="vipType"
                label="会员类型"
              ></el-table-column>
              <el-table-column prop="price" label="金额"></el-table-column>
              <el-table-column
                prop="payTime"
                label="支付时间"
              ></el-table-column>
              <el-table-column prop="status" label="状态">
                <!-- <el-button>支付</el-button> -->
                <template slot-scope="scope">
                  <template v-if="scope.row.status==='待支付'">
                    <el-col :span="6" style="margin: auto 0;">
                      {{ scope.row.status }}
                    </el-col>
                    <el-col :span="12"></el-col>
                    <el-col :span="6">
                      <el-button size="small" @click=" payUnOrder(scope.row.vipOrderId)">去支付</el-button>
                    </el-col>
                  </template>
                  <template v-else>
                    {{ scope.row.status }}
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- Tab 4: 会员续费 -->
          <el-tab-pane label="续费会员" name="renewVip">
            <el-form :model="renewForm" label-width="100px" class="renew-form">
              <!-- 会员类型选择 -->
              <el-form-item label="会员类型">
                <el-select
                  v-model="renewForm.vipType"
                  placeholder="请选择会员类型"
                >
                  <el-option
                    v-for="viptype in vipTypes"
                    :key="viptype.vipTypeId"
                    :label="viptype.vipType"
                    :value="viptype.vipTypeId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- 时长固定为1个月，不允许修改，并在输入框中显示提示文字 -->
              <el-form-item label="续费时长">
                <el-input
                  v-model="renewForm.months"
                  :disabled="true"
                  placeholder="默认1个月"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="renewVip" size="small" style="width: 25%;">续费</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import BreadCrumb from '@/components/user/BreadCrumb.vue'
import { Message } from 'element-ui'
import {
  createVipOrder,
  getVipTypes,
  getVipInfo,
  getVipOrders,
  payByBalance,
  renew
} from '@/api/buyVip'

export default {
  name: 'MemberShip',
  components: {
    BreadCrumb
  },
  data () {
    return {
      activeTab: 'vipTypes',
      vipTypes: [],
      payForm: {
        paymentMethod: '', // 支付方式
        password: '' // 支付密码
      },
      payRules: {
        paymentMethod: [],
        password: []
      },
      paymentDialogVisible: false,
      vipInfoList: [], // 已购会员列表
      vipOrders: [],
      renewForm: {
        vipType: ''
      },
      orderDetail: null,
      vipOrderId: '', // 会员订单id
      orderDetailfb: null,
      isRenewal: false // 新增字段，用于区分支付类型
    }
  },
  created () {
    this.fetchVipTypes()
    this.fetchVipInfo()
    this.fetchVipOrders()
  },
  methods: {
    async fetchVipTypes () {
      const data = await getVipTypes()
      this.vipTypes = data
    },
    async fetchVipInfo () {
      const data = await getVipInfo()
      this.vipInfoList = data
    },
    async fetchVipOrders () {
      const data = await getVipOrders()
      this.vipOrders = data
    },
    purchaseVip (vipTypeId) {
      // console.log(vipTypeId)
      // console.log(this.vipInfoList)
      const isvipType = this.vipInfoList.find((item) => item.vipTypeId === vipTypeId)
      if (!isvipType) {
        this.$confirm('您是否确定购买此会员？', '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const tipMsg = this.getVipOrder(vipTypeId)
          console.log(tipMsg)
          tipMsg.then((value) => {
            this.$message({
              type: 'success',
              message: '购买成功'
            }) // 输出: 成功的值
          }).catch((error) => {
            console.error(error)
          })
        })
          .catch(() => {
            Message.info('已取消购买')
          })
      } else {
        // Message.info('已购买会员,去续费')
        this.$message({
          type: 'warning',
          message: '已购买会员,去续费'
        })
      }
    },
    payUnOrder (vipOrderId) {
      this.paymentDialogVisible = true
      this.vipOrderId = vipOrderId
    },
    confirmOrder () {
      this.paymentDialogVisible = true // 显示支付对话框
      this.vipOrderId = this.createVipOrder(this.orderDetail.vipTypeId)
      this.orderDetail = null
    },
    async getVipOrder (vipTypeId) {
      const res = await createVipOrder(vipTypeId)
      return res
    },
    cancelOd () {
      this.orderDetail = null
    },
    handleTabClick (tab) {
      this.fetchVipTypes()
      this.fetchVipInfo()
      this.fetchVipOrders()
    },
    // 点击续费时
    renewVip () {
      if (!this.renewForm.vipType) {
        Message.error('请选择会员类型')
        return
      }
      this.isRenewal = true // 标记为续费操作
      this.paymentDialogVisible = true // 显示支付对话框
    },
    // 支付订单或者续费
    async payOrder () {
      try {
        if (this.isRenewal) {
          // 续费操作
          this.$refs.payForm.validate(async (value) => {
            const res = await renew(
              this.renewForm.vipType,
              this.payForm.password,
              this.payForm.paymentMethod
            )
            Message.success(res)
          })
        } else {
          // 支付订单操作
          this.$refs.payForm.validate(async (value) => {
            if (value) {
              const res = await payByBalance(
                this.vipOrderId,
                this.payForm.password,
                this.payForm.paymentMethod
              )
              Message.success(res)
              this.vipOrderId = null
            }
          })
        }
        // 支付成功后，重置状态并刷新信息
        this.paymentDialogVisible = false
        this.payForm.password = ''
        this.payForm.paymentMethod = ''
        this.fetchVipInfo()
        this.fetchVipOrders()
      } catch (error) {
        Message.error('支付失败，请重试')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.member-ship-content{
  display: flex;
  justify-content: center;
}
.big-card{
  width: 94%;
}

.vip-types {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 20px;
}

.vip-type-card {
  width: 18%;
  padding: 20px;
  p{
    margin: 10px 0;
  }
}

.order-detail {
  margin-top: 20px;
}

.el-card {
  padding: 20px;
}

// .pay-form{
//   width: 50%;
// }
.renew-form{
  width: 25%;
}
.el-form-item {
  margin-bottom: 20px;
}

.el-table {
  margin: 20px 0;
}
</style>
